/* ===================

AX2E (AXESCON XACML 2.0 Engine) is the Java authorization engine, which implements OASIS XACML 2.0 standard.
Copyright (C) 2007 AXESCON LLC

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


Contact: AXESCON LLC - info{at}axescon.com

 =================== */
package axescon.xacml.engine.alg;

import axescon.xacml.api.*;
import axescon.xacml.api.alg.PolicyCombAlg;
import axescon.xacml.api.alg.PolicyCombAlgFactory;
import axescon.xacml.engine.PolicyEvaluatorImpl;
import axescon.xacml.model.ctx.Result;
import axescon.xacml.model.ctx.XacmlCtx;
import axescon.xacml.model.policy.PolicyCombinerParameters;
import axescon.xacml.model.policy.PolicyObject;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author argyn
 *         Date: Jun 27, 2005
 *         Time: 11:09:19 PM
 *         Responsibilities:
 */
public class BasePolicyCombAlgFactory implements PolicyCombAlgFactory {
    public PolicyCombAlg getPolicyCombAlg(String name) throws XacmlException{
        PolicyCombAlg ret=      (PolicyCombAlg) getPolicyCombAlgs().get(name);
        if(ret==null)throw new XacmlException(name +" alg name is not supported",XacmlException.ERR_CODE_SYNTAX_UNSUPPORTED_COMB_ALG);
        return ret;
    }

    public Result combine(String name, PolicyObject[] policies, XacmlCtx req,
                          CtxHandler ch, PolicyCombinerParameters[] params,
                          PolicyEvaluatorImpl pdp) throws XacmlException {
        return getPolicyCombAlg(name).combine(policies, req, ch, params, pdp);
    }

    /**
     * Map<String, PolicyCombAlg>
     */
    private Map policyCombAlgs;


    /**
     * @return Map<String, PolicyCombAlg>
     */
    public Map getPolicyCombAlgs() {
        return policyCombAlgs;
    }

    public void setPolicyCombAlgs(Map policyCombAlgs) {
        this.policyCombAlgs = policyCombAlgs;
    }

    PolicyCombAlg loadClass(ClassLoader cl, String className) throws XacmlException {
        try {
            return (PolicyCombAlg) cl.loadClass(className).newInstance();
        } catch (Exception x) {
            throw new XacmlException("BasePolicyCombAlgFactory cant load PolicyCombAlg class: " + className, x
                    , XacmlException.ERR_CODE_CLASS_LOAD);
        }

    }

    public void setDefaults() throws XacmlException {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            addAlg(PolicyCombAlg.DENY_OVERRIDES,
                    loadClass(cl, "axescon.xacml.engine.alg.OrderedDenyOverridesPolicyAlg"));
            addAlg(PolicyCombAlg.ORDERED_DENY_OVERRIDES,
                    loadClass(cl, "axescon.xacml.engine.alg.OrderedDenyOverridesPolicyAlg"));
            addAlg(PolicyCombAlg.ORDERED_PERMIT_OVERRIDES,
                    loadClass(cl, "axescon.xacml.engine.alg.OrderedPermitOverridesPolicyAlg"));
            addAlg(PolicyCombAlg.PERMIT_OVERRIDES,
                    loadClass(cl, "axescon.xacml.engine.alg.OrderedPermitOverridesPolicyAlg"));
            addAlg(PolicyCombAlg.FIRST_APPLICABLE,
                    loadClass(cl, "axescon.xacml.engine.alg.FirstApplicablePolicyAlg"));
            addAlg(PolicyCombAlg.ONLY_1_APPLICABLE,
                    loadClass(cl, "axescon.xacml.engine.alg.OnlyOneApplicablePolicyAlg"));
        } catch (Exception e) {
            // all standard classes should load
            throw new XacmlException("BasePolicyCombAlgFactory cant instatiate PolicyCombAlg class", e
                    , XacmlException.ERR_CODE_CLASS_INSTANTIATE);
        }


    }

    public BasePolicyCombAlgFactory() throws XacmlException {
        this(false);
    }

    public BasePolicyCombAlgFactory(boolean isSetDefaults) throws XacmlException {
        setPolicyCombAlgs(new HashMap());
        if (isSetDefaults) setDefaults();
    }


    Logger log = Logger.getLogger(BasePolicyCombAlgFactory.class.getName());

    /**
     * adds combining algorithm to the factory
     * @param urn urn of the algorithm
     * @param alg algorithm object to add
     */
    public void addAlg(String urn, PolicyCombAlg alg) {

        policyCombAlgs.put(urn, alg);
        if (log.isLoggable(Level.CONFIG)) {
            log.config("successfully added to algorithm list (urn,fn): " + urn + ", " + alg.getClass().getName());
        }
    }


    /**
     * this method validates function set
     * @throws XacmlException if syntax error is found
     */
    public void validate() throws XacmlException{

        for(int i=0;i<PolicyCombAlg.MANDATORY_POL_COMB_ALGS.length;i++){

            if(!policyCombAlgs.containsKey(PolicyCombAlg.MANDATORY_POL_COMB_ALGS[i])){
                log.severe("Not loaded mandatory Alg urn:"+PolicyCombAlg.MANDATORY_POL_COMB_ALGS[i]);
            }

        }

    }



}
